from db.mymodel import MyModel
from time import strftime,gmtime

class User(MyModel):
    id_ = 0
    name_ = None
    account_ = None
    amount_ = 0
    password_ = None
    cdate_=None
    #数据库操作实例
    useraccount=None

    def __init__(self):
        self.useraccount=MyModel("useraccount")

    def save(self,addMoney):
        '''存钱方法，useraccount的update方法写入数据库'''
        self.amount_ += float(addMoney)
        data={"id":"%s"%self.id_,"amount":"%s"%str(self.amount_),"cdate":"%s"%self.gettime()}
        self.useraccount.update(data)

    def draw(self,drawMoney):
        '''取钱方法，判断金额是否够用，够用则取钱，然后调用useraccount的update方法写入数据库'''
        if self.amount_ >= float(drawMoney):
            self.amount_ -= float(drawMoney)
            data = {"id": "%s" % self.id_, "amount": "%s" % str(self.amount_),"cdate":"%s"%self.gettime()}
            self.useraccount.update(data)
            return True
        else:
            return False

    def __checpswd(self, pswd):
        '''校验用户输入的密码是否正确，有三次机会，成功返回True，失败返回False'''
        count = 0
        while count < 3:
            self.password_ = input("请输入密码: ")
            if self.password_ == pswd:
                return True
            else:
                count += 1
        return False

    def login(self):
        '''通过用户输入的账号到数据库查询，如果找到账号则要求输入密码，如果没有找到账号则退出'''
        self.account_=input("请输入账号：")
        listuser=self.useraccount.select(["account='%s'"%self.account_])
        if len(listuser)>0:
            print("登录了")
            for i in listuser:
                pass
            if self.__checpswd(i["password"]):
                self.id_=i["id"]
                self.name_=i["name"]
                self.account_=i["account"]
                self.password_=i["password"]
                self.amount_=i["amount"]
                return True
            else:
                print("您输入的密码不对")
        else:
            print("您输入的账号不存在")

    def register(self):
        '''
        这是注册函数，可以注册新的账户，用户输入已经存在的账户提示直接登录
        输入不存在的账户注册新账号
        '''
        registerCount = 0
        self.account_ = input("请输入账号：")
        list=self.useraccount.select(["account='%s'"%self.account_])
        if len(list)>0:
            print("账号已经存在，请重新输入")
            return
        while registerCount < 3:
            self.name_ = input("请输入姓名：")
            pswd = input("请输入密码: ")
            pswdagin = input("请确认密码: ")
            if pswd == pswdagin:
                self.password_= pswdagin
                self.amount_= 0.0
                data={"name":"%s"%self.name_,"account":"%s"%self.account_,"password":"%s"%self.password_,"amount":"%s"%self.amount_,"cdate":"%s"%self.gettime()}
                self.useraccount.insert(data)
                print("密码设置成功，注册账号生效!!!")
                return
            else:
                print("两次密码不一致：")
                registerCount += 1
        print("注册失败！！！")

    def gettime(self):
        self.cdate_=strftime("%Y-%m-%d %H:%M:%S", gmtime())
        return self.cdate_
    def __del__(self):
        pass

#账号操作
def accountaccess():
    '''
	这里是账号操作界面可以做存钱，取钱和查询的操作
	'''
    while True:
        print("欢迎您:{}".format(user.name_))
        print("1.查看账号余额: ")
        print("2.存钱: ")
        print("3.取钱: ")
        print("4.退出账号操作: ")

        choice = input("请输入对应操作的编号: ")

        if choice == "4":
            break
        if choice == "1":
            print("您的账号余额是：{:.02f}".format(user.amount_))
            input("请按回车继续:")
        if choice == "2":
            addMoney = input("您存入的金额是: ")
            user.save(addMoney)
            input("请按回车继续:")
        if choice == "3":
            drawMoney = input("您取出的金额是: ")
            if user.draw(drawMoney):
                pass
            else:
                print("没有足够的钱可以取出")
                input("请按回车继续:")

#程序主入口
if __name__ == '__main__':
    #实例化一个对象
    user = User()
    while True:
        print("=" * 12, "存取钱系统界面", "=" * 12)
        print("1.登录系统")
        print("2.注册新账号")
        print("3.退出")
        print("=" * 40)
        choice = input("请输入对应操作的编号: ")

        # 根据不同的输入进行不同的操作
        if choice == "1":
            print("=" * 12, "存取钱系统登录", "=" * 12)
            if user.login():
                #存取钱操作
                accountaccess()
        elif choice == "2":
            print("=" * 12, "存取钱系统注册", "=" * 12)
            user.register()
        elif choice == "3":
            print("=" * 12, "再见", "=" * 12)
            break
        else:
            print("请输入有效的编号")
